/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.kurvykurvy.page;

import com.kurvykurvy.image.LoadedImage;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Iterator;

/**
 *
 * @author HY
 */
public class PageImpl implements Page
{
    Point frameOffset = new Point( 0, 0 );
    ArrayList<ImageFrame> imageFrames;
    PageLayoutTemplate template;

    public PageImpl( PageLayoutTemplate template )
    {
        if( template != null )
        {
            this.template = template;
        }
        else
        {
            throw new NullPointerException( "Page Template cannot be null" );
        }
    }

    public PageImpl( PageLayoutTemplate template, Point offset )
    {
        this( template );
        
        if( offset != null )
            this.frameOffset = offset;
    }

    public void setPageLayoutTemplate( PageLayoutTemplate template )
    {
        if( template != null && this.template != template )
        {
            this.template = template;
            constructImageFrames();
        }
        else
        {
            throw new NullPointerException( "Page Template cannot be null" );
        }
    }

    public PageLayoutTemplate getPageLayoutTemplate()
    {
        return this.template;
    }

    public ArrayList<ImageFrame> getImageFrames()
    {
        if( this.imageFrames == null )
            constructImageFrames();

        return this.imageFrames;
    }

    public boolean isLeft()
    {
        return this.template.isLeft();
    }

    public boolean isRight()
    {
        return !this.template.isLeft();
    }

    private void constructImageFrames()
    {
        this.imageFrames = new ArrayList<ImageFrame>();
        if( this.template != null && this.template.getImageFrames() != null && !this.template.getImageFrames().isEmpty() )
        {
            for( Iterator<ImageFrameTemplate> it = this.template.getImageFrames().iterator(); it.hasNext(); )
            {
                ImageFrameTemplate frame = it.next();
                ImageFrameTemplate frameClone = (ImageFrameTemplate) frame.clone();
                int xOffset = ( frameOffset != null )? frameOffset.x + frame.getOffset().x : frame.getOffset().x;
                int yOffset = ( frameOffset != null )? frameOffset.y + frame.getOffset().y : frame.getOffset().y;
                Point newOffset = new Point( xOffset, yOffset );
                frameClone.setOffset( newOffset );
                this.imageFrames.add(  ImageFrameFactory.createImageFrame( frameClone, LoadedImage.BLANK_IMAGE ) );
            }
        }
    }
}
